package com.dldata.devtools30.service.sysform;

import com.dldata.devtools30.common.DataListCols;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.entity.DevtFormListtemplArgsEntity;
import com.dldata.devtools30.entity.DevtFormListtemplTheaderEntity;
import com.dldata.devtools30.entity.DevtFormListtemplateEntity;
import com.dldata.devtools30.repository.common.DlBaseJdbcTemplate;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplArgsDao;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplTheaderDao;
import com.dldata.devtools30.repository.sysform.DevtFormListtemplateEntityDao;
import com.dldata.devtools30.utils.DBTypeUtil;
import com.dldata.devtools30.utils.StringUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

/**

 */
@Component
@Transactional
public class DevtFormListTemplateService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DevtFormListtemplateEntityDao sysCrfFormListtemplateDao;

    @Autowired
    private DevtFormListtemplArgsDao sysCrfFormListtemplArgsDao;

    @Autowired
    private DevtFormListtemplTheaderDao sysCrfFormListtemplTheaderDao;

    @Autowired
    private DlBaseJdbcTemplate dlBaseJdbcTemplate;


    public List<DevtFormListtemplateEntity> getDataAll(){
        return sysCrfFormListtemplateDao.getDataAll();
    }

    public List<DevtFormListtemplateEntity> getDataByFl(String flid, String search){
        return sysCrfFormListtemplateDao.getDataByFl(flid,search);
    }

    public List<DevtFormListtemplateEntity> getDataByFl(String flid){
        return sysCrfFormListtemplateDao.getDataByFl(flid);
    }

    public List<DevtFormListtemplateEntity> getDataByName(String search){
        return sysCrfFormListtemplateDao.getDataByName(search);
    }

    public List<DevtFormListtemplateEntity> getFormListtemplateByFormId(String formId){
        return sysCrfFormListtemplateDao.getFormListtemplateByFormId(formId);
    }

    public DevtFormListtemplateEntity getFormActivtyTemplateByFormId(String formId){

        return sysCrfFormListtemplateDao.getFormActivtyTemplateByFormId(formId);
    }


    public DevtFormListtemplateEntity getTemplateById(String templateId){
        return sysCrfFormListtemplateDao.findById(templateId).orElse(null);

    }


    public void save(DevtFormListtemplateEntity customFormTemplateEntity){
//        sysCrfFormListtemplateDao.save(customFormTemplateEntity.getId(),customFormTemplateEntity);
        sysCrfFormListtemplateDao.save(customFormTemplateEntity);
    }

    public Integer getMaxXh(String Flid){
        return sysCrfFormListtemplateDao.getMaxXh(Flid);
    }

    public void saveEntityList(List<DevtFormListtemplateEntity> customFormTemplateEntities){
//        Map<String,SysFormListtemplateEntity> ids = new HashMap<>();
//        customFormTemplateEntities.forEach(e -> {
//            ids.put(e.getId(), e);
//        });
//        sysCrfFormListtemplateDao.save(ids);
        sysCrfFormListtemplateDao.saveAll(customFormTemplateEntities);
    }

    public DevtFormListtemplateEntity getFormActivtyTemplateByFormIdAndType(String formId){
        return sysCrfFormListtemplateDao.getFormActivtyTemplateByFormIdAndType(formId);
    }



    public List<DataListCols> getDataListColses(DevtFormListtemplateEntity sysCrfFormListtemplateEntityOne) throws SQLException {
        StringBuilder templSqlBuilder=new StringBuilder(sysCrfFormListtemplateEntityOne.getTemlplesql());
//        List <SysFormListtemplArgsEntity> sysCrfFormListtemplArgsEntities = sysCrfFormListtemplArgsDao.getAllCloneData();
        List <DevtFormListtemplArgsEntity> sysCrfFormListtemplArgsEntities = Lists.newArrayList( sysCrfFormListtemplArgsDao.findAll());
        List<Object> sqlParameters=new LinkedList<>();
        sysCrfFormListtemplArgsEntities.stream().filter(
                sysCrfFormListtemplArgsEntity1 -> {
                    return sysCrfFormListtemplArgsEntity1.getTempleid().equals(sysCrfFormListtemplateEntityOne.getId());
                }
        ).forEach(
                sysCrfFormListtemplArgsEntity -> {
                    String templSql = templSqlBuilder.toString();
                    String tjsql = sysCrfFormListtemplArgsEntity.getTjsql();
                    if("Number".equalsIgnoreCase(sysCrfFormListtemplArgsEntity.getCslx())){
                        tjsql=tjsql.replace("#values#", "-1");
//                        tjsql="'"+tjsql+"'";
                    }else if(EnumUtils.SEARCHLX.datetime.getValue().toString().equals(sysCrfFormListtemplArgsEntity.getLx().toString())){
                        tjsql=tjsql.replace("#values#", "1970-01-01 00:00:00");
//                        tjsql="'"+tjsql+"'";
                    }else if("String".equalsIgnoreCase(sysCrfFormListtemplArgsEntity.getCslx())|| StringUtil.isEmptyOrLength0(sysCrfFormListtemplArgsEntity.getCslx())){
                        tjsql=tjsql.replace("#values#", "1");
//                        tjsql="'"+tjsql+"'";
                    }
                    templSql = templSql.replaceAll("#" + sysCrfFormListtemplArgsEntity.getArgname() + "#",tjsql);
                    templSqlBuilder.replace(0, templSqlBuilder.length(), templSql);
                }
        );

        Connection connection = DataSourceUtils.getConnection(dlBaseJdbcTemplate.getDataSource());
        HashMap<Integer,String> resultSetDataMap=new HashMap<>();
        try{
            String sqlStr = templSqlBuilder.toString();
            sqlStr=sqlStr.replace("#midvalues#","''");
            sqlStr=sqlStr.replace(" where "," where 1=2 and ");
            sqlStr=sqlStr.replace("\nwhere ","\nwhere 1=2 and ");
            DBTypeUtil.DBTYPE dbtype= DBTypeUtil.getDbtype(dlBaseJdbcTemplate.getDataSource());
            if(DBTypeUtil.DBTYPE.mysql.equals(dbtype)){
                sqlStr=sqlStr.indexOf("order by")>-1?sqlStr.substring(0,sqlStr.indexOf("order by")):sqlStr;
                sqlStr=sqlStr+" limit 1 ";
            }else if(DBTypeUtil.DBTYPE.sqlserver.equals(dbtype)){
                sqlStr="select top 0 "+sqlStr.trim().substring(6);
            }
            logger.info("executeQuery: "+sqlStr);
            ResultSet rest=connection.createStatement().executeQuery(sqlStr);
            ResultSetMetaData resultSetMetaData = rest.getMetaData();
            for (int i=0;i<resultSetMetaData.getColumnCount();i++){
                resultSetDataMap.put(i,resultSetMetaData.getColumnLabel(i+1));
            }
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            throw  ex;
        }finally {
            DataSourceUtils.releaseConnection(connection, dlBaseJdbcTemplate.getDataSource());
        }

        List<DataListCols> dataListColsList = new ArrayList<DataListCols>();
        List <DevtFormListtemplTheaderEntity> sysCrfFormListtemplTheaderEntities = Lists.newArrayList( sysCrfFormListtemplTheaderDao.findAll());
        sysCrfFormListtemplTheaderEntities.stream().filter(
                sysCrfFormListtemplTheaderEntity -> {
                    return sysCrfFormListtemplTheaderEntity.getTempleid().equals(sysCrfFormListtemplateEntityOne.getId());
                }
        ).sorted(
                new Comparator<DevtFormListtemplTheaderEntity>(){
                    public int compare(DevtFormListtemplTheaderEntity o1, DevtFormListtemplTheaderEntity o2) {
                        return o1.getXh()-o2.getXh();
                    }
                }
        ).forEach(
                (sysCrfFormTemplateEntity) -> {
                    DataListCols dataListCols = new DataListCols();
                    dataListCols.field = resultSetDataMap.get(dataListColsList.size());
                    dataListCols.title = sysCrfFormTemplateEntity.getHeadname();
                    dataListCols.width = sysCrfFormTemplateEntity.getWidth()==null||sysCrfFormTemplateEntity.getWidth()==0?15:sysCrfFormTemplateEntity.getWidth();

                    dataListColsList.add(dataListCols);
                }
        );
        return dataListColsList;
    }
}
